package controllers

import play.api._
import play.api.mvc._
import play.api.data._

import anorm._

import models._
import views._

/**
 * Manage projects related operations.
 */
object Projects extends Controller with Secured {
  /**
   * Display the dashboard.
   */
  def index = Action { request =>
    Ok(
      html.dashboard(
        Deck.findInvolving(request.username.get), 
        User.findByEmail(request.username.get).get
      )
    )
  }
  
  /**
   * Add a project.
   */
  def add = Action { implicit request =>
    Form("group" -> requiredText).bindFromRequest.fold(
      errors => BadRequest,
      folder => Ok(
        views.html.decks.item(
          Deck.create(
            Deck(NotAssigned, "New project"), 
            Seq(request.username.get)
          )
        )
      )
    )
  }

  /**
   * Add a new project deck.
   */
  def addDeck = Action { implicit request =>
    Ok(
      views.html.decks.item(
        Deck.create(
          Deck(NotAssigned, "New deck"), 
          Seq(request.username.get)
        )
      )
    )
  }

  /**
   * Delete a project deck.
   */
  def deleteDeck(folder: String) = Action { 
    Deck.deleteInFolder(folder)
    Ok
  }

  /**
   * Rename a project deck.
   */
  def renameDeck(folder: String) = Action { implicit request =>
    Form("name" -> requiredText).bindFromRequest.fold(
      errors => BadRequest,
      newName => { Deck.renameFolder(folder, newName); Ok(newName) }
    )
  }
}
